package top.hkyzf.study.leetcode.hash;

import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

/**
 * @author 朱峰
 * @date 2022-1-24 9:11
 */
public class 无重复字符的最长子串_3 {
    public int lengthOfLongestSubstring(String s) {
        HashSet<Character> set = new HashSet<>();
        char[] charArray = s.toCharArray();
        int right;
        int result = 0;
        for (int i = 0; i < charArray.length; i++) {
            int temp = 1;
            right = i + 1;
            set.add(charArray[i]);
            if (i < charArray.length-1) {
                while (!set.contains(charArray[right])) {
                    set.add(charArray[right]);
                    temp++;
                    right++;
                    if (right >= charArray.length) {
                        break;
                    }
                }
                set.clear();
            }
            result = Math.max(temp, result);
        }
        return result;
    }

    public int lengthOfLongestSubstring1(String s) {
        HashSet<Character> set = new HashSet<>();
        int right = 0;
        int result = 0;
        for (int i = 0; i < s.length(); i++) {
            // 移除之前的字符
            if (i != 0) {
                set.remove(s.charAt(i-1));
            }
            while (right < s.length() && !set.contains(s.charAt(right))) {
                set.add(s.charAt(right));
                right++;
            }
            result = Math.max(result, right - i);
        }
        return result;
    }

    @Test
    public void testLengthOfLongestSubstring () {
        String s = "dvdf";
        System.out.println(lengthOfLongestSubstring1(s));
    }
}
